package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 配置文件解析类
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 解析配置文件
     * @param in    配置文件字节输入流
     * @return
     */
    public Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException {
        // 1. 解析sqlMapConfig.xml配置文件
        // 使用Dom4j读取XML配置文件
        SAXReader reader = new SAXReader();
        Document document = reader.read(in);

        // 获取根节点——即<configuration>
        Element rootElement = document.getRootElement();
        // 通过相应的XPath读取dataSource的相关信息
        List<Element> elementList = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : elementList) {
            // name属性值
            String name = element.attributeValue("name");
            // value属性值
            String value = element.attributeValue("value");
            // 封装到Properties对象中【键-值】
            properties.put(name, value);
        }

        // 利用c3p0连接池解决【频繁连接释放数据库连接的问题】
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("url"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        // 封装到Configuration对象中
        configuration.setDataSource(dataSource);

        // 2. 解析mapper.xml配置文件
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            // mapper.xml配置文件的全路径
            String resource = element.attributeValue("resource");
            // mapper.xml配置文件的字节输入流
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        return configuration;
    }
}
